<?php


namespace App\Repositories;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Config;

abstract class BaseRepository
{
    /**
     * @return Model
     */
    abstract public function model();
    public function pagination($where=[],$param=[]){
        //分页
        $size = (isset($param['size']) && $param['size']) > 0 ? (int)$param['size'] : (int)Config::get('admin.per_page');
        $with = (isset($param['with'])&&$param['with'])?$param['with']:[];
        $whereIn = $param['whereIn']??[];
        $field = $param['field']??['*'];
        $page = $this->model()->when($where, function ($query) use ($where) {
            return $query->where($where);
        })->when($whereIn,function ($query)use($whereIn){
            foreach ($whereIn as $item){
                $query->whereIn($item[0],$item[1]);
            }
        })->when($with,function ($query)use($with){
            return $query->with($with);
        })->select($field)->when(isset($param['order']),function ($query)use($param){
            return $query->orderBy($param['order']['name'],$param['order']['rule']);
        },function ($query){
            return $query->latest();
        })->paginate($size);
        return $page;
    }

    /**
     * @param Model $model
     * @param $data
     * @return bool|Model
     */
    public function update(Model $model, $data){
        return $model->update($data)?$model:false;
    }
    public function save(Model $model,$data){
        return $model->save($data);
    }

    public function tree($where = [], $param = [],$pname='pid',$resetId =0){
        $model = $this->model();
        $parent_id = $param[$pname] ?? $resetId;
        $data = $this->model()->where($where)->get();
        if ($data) {
            return getTree($data->toArray(), $parent_id,$pname);
        } else {
            return [];
        }
    }

}
